<?php


namespace PKApp\Content;

use PKApp\Content\Classes\TraitContent;
use PKApp\Topic\Classes\TraitTopic;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\Excel;
use PKFrame\DataHandler\Numbers;

class AdminGetContent extends AdminController
{

    use TraitContent, TraitTopic;

    private $_catId, $_has_catId, $_categoryEntity;
    private $_is_readMe = false;
    private $_serviceOfContent;

    public function __construct()
    {
        parent::__construct();
        if (request()->action() != 'Main') {
            $this->_serviceOfContent = $this->serviceOfContent(
                $this->getIdOfModel()
            );
        }
    }

    public function Main()
    {
        $this->assign([
            'catId' => $this->getIdOfCategory(),
            'modelId' => $this->getIdOfModel(),
            'attribute' => dict('content_attribute'),
        ])->fetch('content_list');
    }

    // 组合查询条件
    private function _paramsOfQuery(): array
    {
        $where = ['siteId' => $this->loginUser()->SiteId];
        if ($this->_has_catId = request()->has('catId', 'get')) {
            $this->_catId = $this->getIdOfCategory();
            if (Numbers::IsId($this->_catId)) {
                $this->_isPower();
                $where = ['catid' => $this->_catId];
                !$this->_is_readMe ?: $where['userId'] = $this->loginUser()->Id;
            }
        }
        if (toBool('recovery', request()->get())) {
            $where['isDeleted'] = 1;
        }
        if (request()->has('attribute', 'get')) {
            $attribute = request()->get('attribute');
            if (!empty($attribute)) {
                $list_attribute = dict('content_attribute');
                array_key_exists($attribute, $list_attribute) ?: $this->noticeByJson('Content_attribute_Error');
                $where[$attribute] = 1;
            }
        }
        // 筛选方式
        $query = trim(request()->get('query'));
        empty($query) ?: $where['query_like'] = $query;
        return $where;
    }

    public function ApiByExport()
    {
        $project_code = 'export_';
        $query_params = $this->_paramsOfQuery();
        $query_field = ['id', 'title', 'modelId', 'siteId', 'catId', 'url', 'mirroringId'];
        $export_excel_field = dict('export_excel_lang');
        $contentEntityList = $this->_serviceOfContent->GetList($query_params, $query_field);
        if (!is_array($contentEntityList) || count($contentEntityList) == 0) {
            $this->noticeByPage('Content_Empty');
        }
        $excel_cls = new Excel();
        $excel_cls_w = $excel_cls->WriterExcel();
        $excel_cls_ww = $excel_cls->WriterExcelOfXls($excel_cls_w);
        $chr_i = 0;
        foreach ($export_excel_field as $field_cn) {
            $excel_cls_w->getActiveSheet()->setCellValue(chr(65 + $chr_i) . '1', $field_cn);
            $chr_i += 1;
        }
        $i_rows = 2;
        $list_cat = $this->_serviceOfCategory()->GetListById(
            Arrays::Column($contentEntityList, 'catId'));
        $siteEntity = $this->serviceOfSite()->interface_getEntityById($this->loginUser()->SiteId, ['Site_Path']);
        foreach ($contentEntityList as $index => $item) {
            $i_chr = 0;
            foreach ($export_excel_field as $field_en => $field_cn) {
                if ($field_en == 'url' && !Numbers::IsId($item['mirroringId'])) {
                    $value = rtrim(request()->domain(), '/') . $this->getContentUrl($list_cat, $item, $siteEntity);
                } else {
                    $value = $item[$field_en];
                }
                $excel_cls_w->getActiveSheet()->setCellValue(chr(65 + $i_chr) . $i_rows, $value);
                $i_chr += 1;
            }
            $i_rows += 1;
        }
        header("Pragma: public");
        header("Expires: 0");
        ob_end_clean();
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
//header('Cache-Control: max-age=0');
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename={$project_code}_" . TIMESTAMP . ".xls");
        header("Content-Transfer-Encoding:binary");
        $excel_cls_ww->save('php://output');
    }

    public function ApiByLists()
    {
        $where = $this->_paramsOfQuery();
        $this->getPages();
        $count = $this->_serviceOfContent->GetCount($where);
        $contentEntityList = $this->_serviceOfContent->GetList(
            $where,
            ['id', 'title', 'modelId', 'siteId', 'catId', 'thumb', 'listSort', 'hits', 'createTime',
                'toHead', 'toPush', 'toTop', 'url', 'isDeleted', 'mirroringId', 'seoDescription'],
            self::$pageIndex,
            self::$pageSize
        );
        if (Arrays::Is($contentEntityList)) {
            $siteEntity = $this->serviceOfSite()->interface_getEntityById($this->loginUser()->SiteId, ['Site_Path']);
            if (!$this->_has_catId) {
                $list_cat = $this->_serviceOfCategory()->GetListById(
                    Arrays::Column($contentEntityList, 'catId'));
            } else {
                $list_cat = [$this->_categoryEntity];
            }
            foreach ($contentEntityList as $index => $item) {
                if (!Numbers::IsId($item['mirroringId'])) {
                    $item['url'] = $this->getContentUrl($list_cat, $item, $siteEntity);
                }
                $contentEntityList[$index] = $item;
            }
        }
        $this->json($contentEntityList, $count);
    }

    public function ApiGetCountByModelId()
    {
        $count = $this->_serviceOfContent->GetCount([
            'modelId' => Numbers::To(request()->get('modelId'))
        ]);
        $this->json([], $count);
    }

    public function ApiGetDetail()
    {
        $this->_isPower();
        if ($this->_is_readMe) {
            $entity_content = $this->_serviceOfContent->GetEntity([
                'id' => request()->get('id'),
                'userId' => $this->loginUser()->Id,
            ]);
        } else {
            $entity_content = $this->_serviceOfContent->interface_getEntityById(
                request()->get('id')
            );
        }
        $list_mirroring = $this->_serviceOfContent->GetList(['mirroringId' => $entity_content['id']], ['catId']);
        if (Arrays::Is($list_mirroring)) {
            $list_MCatId = Arrays::Column($list_mirroring, 'catId');
            $list_cat = $this->_serviceOfCategory()->GetList(['id' => $list_MCatId], ['id', 'modelId', 'name']);
            $entity_content['mirroring_category'] = $list_cat;
        } else {
            $entity_content['mirroring_category'] = [];
        }
        $list_topic = $this->serviceOfTopicContent()->GetListByIn(['contentId' => $entity_content['id'],
            'siteId' => $this->loginUser()->SiteId, 'contentModelId' => $entity_content['modelId']],
            ['topicId', 'topicTitle', 'topicTypeId', 'topicTypeName']);
        $entity_content['topicList'] = Arrays::Is($list_topic) ? $list_topic : [];
        $this->json($entity_content);
    }

    /**
     * 内容安全 批量检测
     * 按数据模型 ID 遍历
     */
    public function ApiGetDetailByPageIndex()
    {
        $this->getPages('checkIndex');
        $this->json(
            $this->_serviceOfContent->GetEntityByPageIndex(self::$pageIndex)
        );
    }

    /**
     * 检查当前栏目的编辑权限和阅读权限
     */
    private function _isPower()
    {
        $this->_catId = Numbers::To(request()->get('catId'));
        $this->_categoryEntity = $this->_serviceOfCategory()->interface_getEntityById($this->_catId);
        if (array_key_exists('power', $this->_categoryEntity) && is_array($this->_categoryEntity['power'])) {
            $power = $this->_categoryEntity['power'];
            if (array_key_exists('ReadMeGroup', $power) && !empty($power['ReadMeGroup'])) {
//                只能阅读自己的内容
//                在设置范围内的是受控制的范围
                $this->_is_readMe = in_array(
                    $this->loginUser()->GroupId,
                    explode(',', $power['ReadMeGroup'])
                );
            }
        }
    }

    private function _serviceOfCategory()
    {
        return $this->serviceOfCategory(
            $this->loginUser()->SiteId
        );
    }

}
